package lupita.persistence;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySQLImpl implements MySQLInterface {	
	
	private Connection connection; // objeto que representa la coleccion
	private Statement statementSQL; // sentencia de SQL
	private ResultSet result; // conjunto de resultados
	
	private static final String DB = "lupitasearch";
	private static final String USER = "root";
	private static final String PASS = "1123581321";
	private static final String MYSQL_CONTROLLER = "com.mysql.jdbc.Driver";
	private static final String URL_SERVER = "jdbc:mysql://localhost:3306/";
	
	public MySQLImpl()throws Exception {
		
	}
	
	@Override
	public void closeConnection() throws Exception {
		
		if (result != null) result.close();
	    if (statementSQL != null) statementSQL.close();
	    if (connection != null) connection.close();
	}

	@Override
	public int execQuery(String sql) throws SQLException {
		int executeUpdate = statementSQL.executeUpdate(sql);
		return executeUpdate;
	}

	@Override
	public void openConnection() throws Exception {				
		Class.forName(MYSQL_CONTROLLER).newInstance();
		String urlDB = URL_SERVER+DB;
		// Conectar con la BD
		connection = DriverManager.getConnection(urlDB, USER, PASS);		
		// Crear una sentencia de SQL
		statementSQL = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
													ResultSet.CONCUR_UPDATABLE);
	}

	@Override
	public ResultSet selectSQL(String sql) throws SQLException {
		result = statementSQL.executeQuery(sql);		
		return result;
	}
}